package com.qhy.myrules;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author qiuhongyu
 * @date 2020/10/10 9:58
 */
public class QhyRandomRule extends AbstractLoadBalancerRule {

    //每个服务，访问5次，然后换下一个服务（此案例中有3个）
    //total=0,默认为0，如果为5，就指向下一个服务节点
    //index=0,默认0，如果total=5,index+1
    private int total = 0;//被调用的次数
    private int currentIndex = 0;//当前是谁再提供服务

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        Server server = null;

        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            //获得活着的服务
            List<Server> upList = lb.getReachableServers();
            //获得全部服务
            List<Server> allList = lb.getAllServers();

            int serverCount = allList.size();
            if (serverCount == 0) {
                return null;
            }
//            //生成区间随机数
//            int index = chooseRandomInt(serverCount);
//            //从或活着的服务中随机获取一个
//            server = upList.get(index);
            //=======================================================
            //改造算法
            if (total < 5) {
                server = upList.get(currentIndex);
                total++;
            }else {
                total =0 ;
                currentIndex++;
                if (currentIndex>upList.size()) {
                    currentIndex = 0;
                }
                server = upList.get(currentIndex);//从活着的服务中，获取指定的服务来操作
            }
                //======================================================

                if (server == null) {
                    /*
                     * The only time this should happen is if the server list were
                     * somehow trimmed. This is a transient condition. Retry after
                     * yielding.
                     */
                    Thread.yield();
                    continue;
                }

            if (server.isAlive()) {
                return (server);
            }

            // Shouldn't actually happen.. but must be transient or a bug.
            server = null;
            Thread.yield();
        }

        return server;

    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        // TODO Auto-generated method stub

    }
}
